package v1

import (
	"gateway-api/controllers"
	"gateway-api/proto/user"
	pbUser "gateway-api/proto/user"
	"gateway-api/tools"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

/*
 +----------------------------------------------------------------------
 + Title        : UserController
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2020-11-23
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 用户控制层
 +----------------------------------------------------------------------
*/
type UserController struct {
	controllers.BaseController
}

/**
 * 登录
 *
 * @param string username -----------------------------------必传,用户名
 * @param string password -----------------------------------必传,密码
 * @return Json
 * @author huwl
 */
func (control UserController) Login(ctx *gin.Context) {
	username := ctx.DefaultPostForm("username", "")
	password := ctx.DefaultPostForm("password", "")
	if username == "" {
		control.BaseError(ctx, control.WithMessage("请输入用户名"))
		return
	}
	if password == "" {
		control.BaseError(ctx, control.WithMessage("请输入密码"))
		return
	}

	userSrvClient := pbUser.NewUserSrvClient(tools.UserServiceClientConn)
	userResult, err := userSrvClient.Row(ctx, &pbUser.QueryUserRequest{
		Username: username,
		Status:   "1",
	})
	if err != nil {
		control.BaseError(ctx, control.WithGrpcError(err))
		return
	}

	if !tools.CompareBcrypt(userResult.User.Password, password) {
		control.BaseError(ctx, control.WithMessage("密码错误"))
		return
	}

	token, err := tools.GenerateToken(strconv.Itoa(int(userResult.User.Uid)))
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	// 生成refreshToken
	refreshToken := uuid.New().String()
	// 需要将refreshToken存入redis
	ri, err := tools.NewRedisInstance()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	err = ri.RedisSet("userRefreshToken:"+strconv.FormatInt(userResult.User.Uid, 10), refreshToken, time.Hour*12*10)
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(ctx, control.WithData(gin.H{
		"user":              userResult.User,
		"token":             token,
		"token_expire_time": time.Now().Add(tools.TokenExpireTime).Unix(),
		"refresh_token":     refreshToken,
	}), control.WithMessage("登录成功"))
}

/**
 * 注册
 *
 * @param string username -----------------------------------必传,用户名
 * @param string password -----------------------------------必传,密码
 * @param string repassword ---------------------------------必传,重复密码
 * @param string mobile -------------------------------------必传,手机号
 * @param string email --------------------------------------必传,邮箱
 * @param string captcha ------------------------------------必传,验证码
 * @param string captcha_id ---------------------------------必传,验证码ID
 * @return Json
 * @author huwl
 */
func (control UserController) Register(ctx *gin.Context) {
	username := ctx.DefaultPostForm("username", "")
	password := ctx.DefaultPostForm("password", "")
	repassword := ctx.DefaultPostForm("repassword", "")
	mobile := ctx.DefaultPostForm("mobile", "")
	email := ctx.DefaultPostForm("email", "")
	// captcha := ctx.DefaultPostForm("captcha", "")
	// captchaId := ctx.DefaultPostForm("captcha_id", "")

	if username == "" {
		control.BaseError(ctx, control.WithMessage("请输入用户名"))
		return
	}
	if password == "" {
		control.BaseError(ctx, control.WithMessage("请输入密码"))
		return
	}
	if repassword == "" {
		control.BaseError(ctx, control.WithMessage("请输入确认密码"))
		return
	}
	if password != repassword {
		control.BaseError(ctx, control.WithMessage("两次密码要输入一致哦"))
		return
	}
	if !tools.CheckMobile(mobile) {
		control.BaseError(ctx, control.WithMessage("请输入正确格式的手机号"))
		return
	}
	if !tools.CheckEmail(email) {
		control.BaseError(ctx, control.WithMessage("请输入正确格式的邮箱"))
		return
	}

	//判断验证码
	// b := tools.ValidateCaptcha(captchaId, captcha)
	// if !b {
	// 	control.BaseError(ctx, "验证码错误")
	// 	return
	// }

	userSrvClient := pbUser.NewUserSrvClient(tools.UserServiceClientConn)
	_, err := userSrvClient.AddUser(ctx, &user.AddUserRequest{
		Username: username,
		Password: password,
		Mobile:   mobile,
		Email:    email,
		Status:   1,
	})
	if err != nil {
		control.BaseError(ctx, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(ctx, control.WithData("用户注册成功"))
}

/**
 * 用户详情
 *
 * @return Json
 * @author huwl
 */
func (control UserController) Detail(ctx *gin.Context) {
	uid, _ := ctx.Get("uid")
	userId, _ := strconv.ParseInt(uid.(string), 10, 64)

	userSrvClient := pbUser.NewUserSrvClient(tools.UserServiceClientConn)
	result, err := userSrvClient.UserDetail(ctx, &pbUser.UserDetailRequest{Uid: userId})
	if err != nil {
		control.BaseError(ctx, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(ctx, control.WithData(gin.H{
		"user":        result.User,
		"user_albums": result.UserAlbums,
	}))
}
